package com.jiyi.easemob.view;

import android.util.Log;
import android.view.View;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.ui.EaseChatFragment.EaseChatFragmentHelper;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.jiyi.bean.zone.HuoDongDetailJson;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.bean.EasemobUser;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.util.EaseCacheUtil;
import com.jiyi.event.HaoYouListEvent;
import com.jiyi.event.QunZuListEvent;
import com.jiyi.inteface.HuoDongPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.HuoDongPopView;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ChatFragment extends EaseChatFragment implements
		EaseChatFragmentHelper ,HuoDongPopInterface{

	// 消息类型
	private String msgTp = "";
	/**
	 * 该头像地址传过来是就是完整的路径
	 * */
	private String userpic = "";
	private String id, name, groupid;

	//保存当前最新的互动时间，如果互动时间没改变就不上传到服务器
	private Long lastTime=0L,temp ;
	//是否分享活动
	private boolean isShareHuoDong = false;

	HuoDongPopView mHuoDongPopView;

	@Override
	protected void setUpView() {
		// 注册消息行点击监听
		setChatFragmentListener(this);
		super.setUpView();
		msgTp = getArguments().getString(ClouldChatType.INTENT_MSG_TP);
		userpic = getArguments().getString(ClouldChatType.INTENT_USER_PIC);
		groupid = getArguments().getString(ClouldChatType.INTENT_Group_Id);
		chatType = getArguments().getInt(EaseConstant.EXTRA_CHAT_TYPE, 0);
		id = getArguments().getString("id");
		name = getArguments().getString("name");

		isShareHuoDong = getArguments().getBoolean("isShareHuoDong");
		if (isShareHuoDong) {
			ZoneHuoDongBean zoneHuoDongBean = new Gson().fromJson(getArguments().getString("zhiDingHuoDong"), ZoneHuoDongBean.class);
			Log.e("输出活动对象：", new Gson().toJson(zoneHuoDongBean));
			//自定义活动消息类型
	        EMMessage message = EMMessage.createTxtSendMessage("[活动]", toChatUsername);
	        // 增加自己特定的属性
	        message.setAttribute("type", "huodong");
	        //活动id
	        message.setAttribute("huoDongId", zoneHuoDongBean.getId());
	        //活动标题
	        message.setAttribute("huoDongName", zoneHuoDongBean.getTheme());
	        //活动时间
	        message.setAttribute("huoDongDate", zoneHuoDongBean.getStart_time());
	        //活动地址
	        message.setAttribute("huoDongAddress", zoneHuoDongBean.getAddress());
	        //活动封面
	        message.setAttribute("huoDongCover", zoneHuoDongBean.getCover());
	        //活动状态
	        message.setAttribute("huoDongFlag", zoneHuoDongBean.getFlag());
			sendMessage(message);
		}
		mHuoDongPopView = new HuoDongPopView(getContext(), this);
	}

	@Override
	protected void sendMessage(EMMessage message) {
		if (null == message) {
			return;
		}

		String nickName = UserInfoUtil.getCurrentUserName();
		String avatar = UserInfoUtil.getCurrentUserLogo();
		String memberId = UserInfoUtil.getCurrentUserId()+"";
		String easeUid = UserInfoUtil.getCurrentUserAccount();

		// 发送消息统一设置拓展属性，如用户昵称和头像等
		message.setAttribute(ClouldChatType.EASE_CHAT_USER_NICK, nickName);// 昵称
		message.setAttribute(ClouldChatType.EASE_CHAT_USER_PIC, avatar);// 头像
		message.setAttribute(ClouldChatType.EASE_CHAT_RECEIVE_PIC, userpic);// 对方的头像
																			// 如果是圈聊就是圈头像
																			// 私信就是对方用户的头像
																			// 注意！
																			// 该头像地址传过来是就是完整的路径

		// 用户云上的id
		message.setAttribute(ClouldChatType.EASE_CHAT_MEMBER_ID, memberId);// 云memberid
		// 用户环信id
		message.setAttribute(ClouldChatType.EASE_CHAT_USER_ID, easeUid);// 用户名，这里指手机号
		// 圈云上id
		message.setAttribute(ClouldChatType.EASE_CHAT_messageId, groupid);// 圈云上的id
		// 圈环信id
		message.setAttribute(ClouldChatType.EASE_CHAT_easemobId,
				message.getTo());// 圈环信上的id

		message.setAttribute(ClouldChatType.EASE_CHAT_TYPE, msgTp);// 聊天类型
		message.setAttribute(ClouldChatType.EASE_CHAT_MENBER_NAME, name);// 聊天对象

		// 保存用户
		EaseCacheUtil.getInstance().saveEaseMobUser(nickName, avatar, memberId,
				easeUid);

		super.sendMessage(message);
		temp = lastTime;
		lastTime = new Date().getTime();
	}

	/**
	 * 设置消息扩展属性
	 */
	@Override
	public void onSetMessageAttributes(EMMessage message) {
		// TODO Auto-generated method stub

	}

	/**
	 * 进入会话详情
	 */
	@Override
	public void onEnterToChatDetails() {
		// TODO Auto-generated method stub

	}

	/**
	 * 用户头像点击事件
	 *
	 * @param username
	 */
	@Override
	public void onAvatarClick(String username) {
		EasemobUser easemobUser = EaseCacheUtil.getInstance().getEaseMobUser(
				username);
		if (easemobUser == null) {
			Log.e("用户头像点击事件", "该用户不存在");
			return;
		}
//		Intent intent = new Intent(getActivity(), PersonInfoActivity.class);
//		intent.putExtra("id", easemobUser.getMemberId());
//		startActivity(intent);
	}

	/**
	 * 用户头像长按事件
	 *
	 * @param username
	 */
	@Override
	public void onAvatarLongClick(String username) {
		// TODO Auto-generated method stub

	}

	/**
	 * 消息气泡框点击事件
	 */
	@Override
	public boolean onMessageBubbleClick(EMMessage message) {
		try {
			String type = message.getStringAttribute("type");
			if (type.equals("huodong")) {
				Log.e("onMessageBubbleClick ", "onMessageBubbleClick");
				getHuoDongDetail(message.getStringAttribute("huoDongId"));
			}
		} catch (HyphenateException e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 消息气泡框长按事件
	 */
	@Override
	public void onMessageBubbleLongClick(EMMessage message) {
		// TODO Auto-generated method stub

	}

	/**
	 * 扩展输入栏item点击事件,如果要覆盖EaseChatFragment已有的点击事件，return true
	 *
	 * @param view
	 * @param itemId
	 * @return
	 */
	@Override
	public boolean onExtendMenuItemClick(int itemId, View view) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 设置自定义chatrow提供者
	 *
	 * @return
	 */
	@Override
	public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
//		return new HuoDongChatRowProvider(getActivity());
		return null;
	}

	@Override
	public void onPause() {
		super.onPause();
		// 根据当前时间与上次上传的时候判断是否有需要上传互动时间
		if (lastTime > 0 && lastTime > temp) {
			postUpdateTime();
		}

	}

	void postUpdateTime() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("type", (chatType == EaseConstant.CHATTYPE_SINGLE ? EaseConstant.CHATTYPE_SINGLE : EaseConstant.CHATTYPE_GROUP)+"");

		VolleyRequest.StringRequestPost(getActivity(),
				WebApi.ZONE_HAOYOU_ACCESS_TIME, "", params,
				new StringInterface(getActivity()) {

					@Override
					public void stringSuccess(String result) {
						Log.e("postUpdateTime ", result);
						//更新上传时间
						temp = lastTime;
						if (chatType == EaseConstant.CHATTYPE_SINGLE) {
							EventBus.getDefault().postSticky(new HaoYouListEvent(HaoYouListEvent.MY_HAOYOU_FRAGMENT));
						}
						else {
							EventBus.getDefault().postSticky(new QunZuListEvent(QunZuListEvent.MY_QUNZU_FRAGMENT));
						}
					}

					@Override
					public void stringError(VolleyError error) {
						Log.e("postUpdateTime ", error.getMessage());
					}
				});
	}

	/**
	 * <p>Title: OnSureListener</p>
	 * <p>Description: </p>
	 * @see com.jiyi.inteface.HuoDongPopInterface#OnSureListener()
	 */
	@Override
	public void OnSureListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>Title: OnCancleListener</p>
	 * <p>Description: </p>
	 * @see com.jiyi.inteface.HuoDongPopInterface#OnCancleListener()
	 */
	@Override
	public void OnCancleListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>Title: OnShowListener</p>
	 * <p>Description: </p>
	 * @see com.jiyi.inteface.HuoDongPopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>Title: OnHideListener</p>
	 * <p>Description: </p>
	 * @see com.jiyi.inteface.HuoDongPopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub

	}

	void getHuoDongDetail(String huoDongId) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", huoDongId);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.ZONE_HUODONG_DETAIL, "", params, new StringInterface(
						getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								HuoDongDetailJson temp = new Gson().fromJson(
										result, HuoDongDetailJson.class);
								mHuoDongPopView.showPopWindow(temp.getData());
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
}
